package com.expert.interceptor;

import com.expert.annotations.RoleAnnotation;
import com.expert.context.BaseContext;
import com.expert.enums.RoleLevel;
import com.expert.exception.AccountLockedException;
import com.expert.exception.BaseException;
import com.expert.exception.InsufficientPromissionException;
import com.expert.pojo.Role;
import com.expert.pojo.User;
import com.expert.service.RoleService;
import com.expert.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import java.lang.reflect.Method;

/**
 * @ClassName: RoleInterceptor
 * @Author: cxs
 * @Date: 2024/02/07 14:19
 * @Description:
 **/
@Component
@Slf4j
public class RoleInterceptor implements HandlerInterceptor {
    @Autowired
    UserService userService;
    @Autowired
    RoleService roleService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        log.info("拦截权限");
        HandlerMethod handlerMethod=(HandlerMethod) handler;
        Method method=handlerMethod.getMethod();
        RoleAnnotation annotation = method.getAnnotation(RoleAnnotation.class);
        if (annotation==null){
            //注解为空，说明不需要拦截，直接放行
            log.info("注解为空");
            return true;
        }
        User loginUser = userService.getUserById(BaseContext.getCurrentId());
        if(loginUser.getStatus()==0){
            log.info("账号被禁用");
            throw new AccountLockedException();
        }
        //如果是所有都能访问的权限，直接放行
        if (annotation.level().getCode()==RoleLevel.ALL.getCode()){
            log.info("权限为所有用户");
            return true;
        }

        Role loginRole = roleService.getById(loginUser.getRole());
        if (loginRole.getRoleLevel()<annotation.level().getCode()){
            log.error("权限不足");
            throw new InsufficientPromissionException();
        }
        return true;
    }
}
